/**
 * Created by Administrator on 2018/11/6 0006.
 */
/*
* 用户token表
* */
const mongoose = require('mongoose');
const tokenSchema = mongoose.Schema({
    userId: String,  //用户id
    id: {
        type: mongoose.Types.ObjectId
    }
},{timestamps: {createdAt: 'createTime'}})

tokenSchema.statics = {
    //token的校验
    validToken: function(_id) {
        const validTime = 1000 * 60 * 60 * 24;  //token有效期为一天
        return new Promise((resolve,reject) => {
            if(!/^[0-9a-fA-F]{24}$/.test(_id)) {  //对ObjectId的一个格式校验
                resolve(false);
                return;
            }
            this.findOne({_id},(err,data) => {
                if(err) {
                    resolve(9999);
                }else {
                    if(!data) {
                        resolve(false);
                    }else {
                        const nowTime = Date.now();
                        if(nowTime - new Date(data.createTime).getTime() > validTime) {   //过期
                            resolve(false);
                        }else {
                            resolve(true);
                        }
                    }
                }
            })
        })

    },
}

const TokenModel = mongoose.model('token',tokenSchema); //创建集合（表）
module.exports = TokenModel;